package cool.taomu.toolkit.jooq.provider

import com.google.inject.Inject
import com.google.inject.Provider
import com.google.inject.assistedinject.Assisted
import com.google.inject.assistedinject.AssistedInject
import com.google.inject.name.Named
import javax.sql.DataSource
import org.eclipse.xtend.lib.annotations.ToString
import org.jooq.DSLContext
import org.jooq.SQLDialect
import org.jooq.impl.DSL
import org.jooq.tools.jdbc.JDBCUtils
import org.slf4j.LoggerFactory

@ToString
class JooqAssistedProvider implements Provider<DSLContext> {

    val static LOG = LoggerFactory.getLogger(JooqAssistedProvider);

    DataSource ds;

    @AssistedInject
    new(@Assisted DataSource ds) {
        this.ds = ds;
    }

    @Inject(optional=true)
    @Named("taomu.jooq.url")
    String url;

    @Inject(optional=true)
    @Named("taomu.jooq.dialect")
    String dialect

    override get() {
        var SQLDialect sqlDialect = null;
        if (dialect === null) {
            sqlDialect = JDBCUtils.dialect(url);
        } else {
            sqlDialect = SQLDialect.valueOf(dialect.toUpperCase)
        }
        DSL.using(ds, sqlDialect)
    }

    static interface JooqFactory {
        def JooqAssistedProvider create(@Assisted("dataSource") DataSource dataSource)
    }
}
